package test.top1.com.atguigu.utils;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;
import test.top1.com.atguigu.bean.TableProcess;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: JDBCUtil
 * Package: test.top1.com.atguigu.utils
 * Description:
 *
 * @Author ChenJun(有志男青年)
 * @Create 2023/4/27 16:14
 * @Version 1.0
 */
public class JDBCUtil {

    public static <T> List<T> queryList(Connection connection, String sql, Class<T> clz, boolean underScoreToCamel) throws Exception {

        //创建集合存放对象
        ArrayList<T> list = new ArrayList<>();

        //预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //执行查询sql
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();


        // 遍历resultSet,将每行数据封装为T对象
        while (resultSet.next()){

            // 创建t对象
            T t = clz.newInstance();

            for (int i = 1; i < columnCount+1; i++) {

                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                if (underScoreToCamel){
                    columnName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName.toLowerCase());
                }

                BeanUtils.setProperty(t,columnName,value);
            }

            //将对象添加到集合
            list.add(t);
        }

        //返回集合
        return list;
    }


    public static void main(String[] args) throws Exception {
//        DruidPooledConnection connection = DruidDSUtil.getPhoenixConn();

        Connection connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall_config?" +
                "user=root&password=000000&useUnicode=true&" +
                "characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        List<TableProcess> jsonObjects = queryList(connection, "select  * from table_process", TableProcess.class, true);

        for (TableProcess jsonObject : jsonObjects) {
            System.out.println(jsonObject);
        }


        connection.close();
    }
}
